import asyncio
import json
import os
import time
from contextlib import asynccontextmanager
from datetime import datetime
from fastapi import FastAPI, APIRouter, Request
from pydantic import BaseModel
from bilibili.bilibili_scrawler import task_bilibili
from douyin.douyin_scrawler import task_douyin
from common.feishu_api import sendToFeishu
from kuaishou.kuaishou_scrawler import task_kuaishou
from common.redis_util import delete_lock
from bilibili.bilibili_scrawler import THIS_UPDATE_TIME, THIS_REQUEST_TIME
from xiaohongshu.xiaohongshu_crawler import task_xiaohongshu

ISOK = False

router = APIRouter()

LOCK = False

async def bilibili_script(now):
    message = f"🚀 BiliBili脚本开始执行\n开始时间：{THIS_UPDATE_TIME}\n当前时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
    sendToFeishu(message)
    print(message)
    retries = 0
    while retries < 3:
        try:
            await asyncio.to_thread(task_bilibili, now)
            return
        except Exception as e:
            error = str(e)
            print(error)
            retries += 1

    message = f"❌ BiliBili脚本执行失败\n开始时间：{THIS_UPDATE_TIME}\n当前时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n耗时：{time.perf_counter() - now}秒\n错误信息：{error}"
    print(message)
    sendToFeishu(message)


async def douyin_script(now):
    message = f"🚀 DouYin脚本开始执行\n开始时间：{THIS_UPDATE_TIME}\n当前时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
    sendToFeishu(message)
    print(message)
    retries = 0
    while retries < 3:
        try:
            await asyncio.to_thread(task_douyin,now)
            return
        except Exception as e:
            error = str(e)
            print(error)
            retries += 1

    message = f"❌ DouYin脚本执行失败\n开始时间：{THIS_UPDATE_TIME}\n当前时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n耗时：{time.perf_counter() - now}秒\n错误信息：{error}"
    print(message)
    sendToFeishu(message)


async def kuaishou_script(now):
    message = f"🚀 Kuaishou脚本开始执行\n开始时间：{THIS_UPDATE_TIME}\n当前时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
    sendToFeishu(message)
    print(message)
    retries = 0
    while retries < 3:
        try:
            await asyncio.to_thread(task_kuaishou,now)
            return
        except Exception as e:
            error = str(e)
            print(error)
            retries += 1

    message = f"❌ Kuaishou脚本执行失败\n开始时间：{THIS_UPDATE_TIME}\n当前时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n耗时：{time.perf_counter() - now}秒\n错误信息：{error}"
    print(message)
    sendToFeishu(message)
  
async def xiaohongshu_script(now):
    message = f"🚀 Xiaohongshu脚本开始执行\n开始时间：{THIS_UPDATE_TIME}\n当前时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
    sendToFeishu(message)
    print(message)
    retries = 0
    while retries < 3:
        try:
            await asyncio.to_thread(task_xiaohongshu,now)
            return
        except Exception as e:
            error = str(e)
            print(error)
            retries += 1

    message = f"❌ Xiaohongshu脚本执行失败\n开始时间：{THIS_UPDATE_TIME}\n当前时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n耗时：{time.perf_counter() - now}秒\n错误信息：{error}"
    print(message)
    sendToFeishu(message)


@router.post("/invoke")
async def invoke_api(request: Request):
    body_bytes = await request.body()
    print(body_bytes)
    try:
        body = json.loads(body_bytes.decode("utf-8")) if body_bytes else None
    except Exception:
        return {"message" : "cannot parse json"}
    if body == None:
        return {"message" : "no body"}

    print(body)
    print(json.loads(body["payload"]))
    payload = json.loads(body["payload"])

    if payload['type'] == "exit":
        sendToFeishu("✅ 进程被手动停止")
        os._exit(0)
    elif payload['type'] == "run":
        pass
    else:
        return {"message": "Invalid request"}


    global LOCK
    if LOCK:
        message = f"⚠️ 启动失败\n开始时间：{THIS_UPDATE_TIME}\n当前时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n错误信息：脚本正在执行中，稍后再试"
        sendToFeishu(message)
        return {"message": "脚本正在执行中，请稍后再试"}
    
    print("🚀 脚本开始执行")
    LOCK  = True

    now = time.perf_counter()
    await asyncio.gather(
        bilibili_script(now),
        douyin_script(now),
        kuaishou_script(now),
    )

    # now = time.perf_counter()
    # await xiaohongshu_script(now)
    LOCK = False

@router.get("/health")
def health():
    return {"status": "ok","ISOK" : THIS_REQUEST_TIME}

@asynccontextmanager
async def lifespan(app: FastAPI):
    delete_lock("lock:scrawler:bilibili_scrawler")
    print("Starting FastAPI application...")
    yield
    print("FastAPI application closed.")

app = FastAPI(lifespan=lifespan)
app.include_router(router,tags=["CG-F2503003-cron"])

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=80)